<template>
  <div class="content" v-title data-title="一元享起45天">
    <div class="activity-details">
      <div class="banner"><div class="red-card"></div></div>
      <div class="main">
        <div class="activate" v-if = " type=== 0" >
          <div class="input-box">
            <input type="text" v-model="ticketCode" placeholder="刮开卡背面涂层，输入激活密钥" :disabled="ban == true?true:false"/>
          </div>
          <p class="hint" v-show='hint.length>0'>{{hint}}</p>
          <div class="activate-btn" @click="activate" :class="{disable:ban}">确认激活</div>
        </div>
        <div class="payment" v-else-if = " type=== 1 " >
          <p class="key">{{ticketCode}} <span>已激活</span></p>
          <p class="activation-hint">请在<span>{{oHour}}</span>小时<span>{{oMin}}</span>分<span>{{oSec}}</span>秒内完成支付逾期卡片将失效</p>
          <div class="purchase-btn" @click="buySuite(productId)">前往9.8元购买</div>
        </div>
        <div class="finish" v-else-if = " type=== 2 " >
          <p class="key">{{ticketCode}} <span :class = "{'status2':ban,'status1':!ban}">{{status}}</span></p>
          <p class="activation-hint">有效期：{{productOrderPayTime}} 至 {{productOrderExpireTime}}</p>
        </div>
        <div class="finish" v-else>
          <div v-show='timeout'>
            <p class="activation-hint">请登录【六个轮子】APP激活</p>
            <div class="purchase-btn" @click="downloadApp">下载APP</div>
          </div>
        </div>
      </div>
    </div>
    <div class="activity-rules">
      <div class="rules-title"><p>活动规则</p></div>
      <div class="rules-text">
        <p><span>01</span>本卡需在4月1日（含）前激活，逾期无法使用。</p>
        <p><span>02</span>领卡方式：活动期间，在六个轮子的合作商户参与活动，即可获赠六个轮子9.8元骑30天专享卡。数量有限，先到先得。</p>
        <p><span>03</span>激活方式：刮开卡背面涂层，在六个轮子APP活动页输入激活密钥后，即可9.8元购买骑行卡。</p>
        <p><span>04</span>激活后9.8元购买权保留24小时，逾期失效；每人只能购1次。</p>
        <p><span>05</span>骑行有效期30天，从购买日起至第30天24时失效。</p>
        <p><span>06</span>有效期间每天可免费骑行4次，每次限10分钟内免费骑行，超出时长正常计费。</p>
        <p><span>07</span>保险费不包含在本卡套餐中，每次骑行保险费0.2元从充值余额中扣除。</p>
        <p><span>08</span>成功购买本骑行卡后，产生的费用不予退还。</p>
        <p><span>09</span>本卡与其他优惠不并行享用，还车时选择此优惠套餐扣费。</p>
        <p><span>10</span>骑行前需缴纳押金，退押金后无法继续骑车，已购买的卡券有效期不变；重新缴纳押金后，权益立即恢复</p>
        <p><span>11</span>已购买的骑行卡可在最新版本客户端，个人中心-我的套餐 查看。</p>
      </div>
    </div>
    <div class="thumbImg">
      <img :src="require('../styles/asset/tripCard/meituan1.jpg')" />
    </div>
    <div class="thumbImg">
      <img :src="require('../styles/asset/tripCard/meituan2.png')" />
    </div>
    <div class="thumbImg">
      <img :src="require('../styles/asset/tripCard/meituan3.png')" />
    </div>
    <simplert ref="simplert"></simplert>
  </div>

</template>

<script>
  import Simplert from '../../components/dialog/dialog.vue';
  // 获取参数方法
  let filters = {
    parseURL:function(url) {
      let a = document.createElement('a');
      a.href = url;
      return {
        params: (function () {
            if(a.href.split('?').length > 2)
            {
                return false;
            }else{
              let ret = {},
                param = a.href.split('?')[1],
                seg = param.split('&'),
                len = seg.length,
                i = 0,
                s;
              for (; i < len; i++) {
                if (!seg[i]) {
                  continue;
                }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
              }
              return ret;
            }
        })()
      }
    }
  };
  export default {
    data () {
      return{
        'type':'',
        'ticketCode':'',
        'token':'',
        'hint':'',//提示语
        'productId':'',//付款金额
        'ticketCode':'', //卡号
        'ban':false, //禁止操作
        'status':'已生效',
        'Method':'',
        'oDay':'',
        'oHour':'',
        'oMin':'',
        'oSec':'',
        'activeTime':'',//激活时间
        'expireTimes':'',//券码过期时间
        'useExpireTime':'',//激活后使用时间
        'outApp':false,
        'img': require('../styles/asset/share.jpg'),
        'productOrderPayTime':'',
        'productOrderExpireTime':'',
        'timeout':false
      }
    },
    components: {
      Simplert
    },
    mounted(){
      let root = process.env.MAIN_ROOT;
      // console.log(root+this.img)
      this.$util.sendShareMessage("2018 骑出去，旺财到！","9.8元骑30天，齐迎新春", root+this.img);
      var _this=this;
      const url = window.location.href;
      if(filters.parseURL(url).params === false){
        this.outApp = true;
      }
      this.id = filters.parseURL(url).params.id;
      setTimeout(function(){
        _this.timeout=true;
      },800)
      this.$util.getUserToken().then(token=>{
        _this.token = token;
        _this.getSuiteId();
      // })
         _this.info();
      });

    },
    methods:{
      open (title, useCancelBtn,confirmBtn,customConfirmBtnText,onConfirm,type,onClose,message) {
        let obj = {
          title: title,
          useConfirmBtn: confirmBtn,
          useCancelBtn: useCancelBtn,
          customConfirmBtnText: customConfirmBtnText,
          onConfirm:onConfirm,
          type: type,
          onClose:onClose,
          message:message
        };
        console.log(this.$refs);
        this.$refs.simplert.openSimplert(obj);
      },
      info(){
        let _this = this;
        _this.$api.post('/ticket/v1/authApi/activityAndTicket?activityId='+this.id, {}, s => {
          let t = s.module.activityDetailDto;
          let e = s.module.ticketCardDto;
          // 活动过期判断
          let ms = t.endTime - new Date().getTime();//时间差
          if(ms<=0){
            _this.ban = true;
            _this.status = '已失效';
            return false;
          }
          if(e == null){
              _this.type = 0;
              _this.hint = '';
            }else{
              _this.type = Number(e.state);
              _this.productId = e.productId;
              // alert(_this.productId);
              _this.ticketCode = e.ticketCode;

              // _this.activeTime = _this.formatDate(e.activeTime);
              // _this.expireTimes  = _this.formatDate(e.expireTime);
              _this.productOrderPayTime  = _this.formatDate(e.productOrderPayTime);
              _this.productOrderExpireTime  = _this.formatDate(e.productOrderExpireTime);
              if (_this.type == 1){//已激活
                _this.useExpireTime = e.useExpireTime;
                _this.expireTime();
                _this.Method=setInterval(_this.expireTime,1000);
              }
              else if ( _this.type == 2 ){ //已生效

                // _this.activeTime = e.activeTime;
                // _this.expireTimes  = e.expireTime;
              }
            };
        },f=>{
              this.open('检查失败,重新再试',false,false,'','','fade_alert',function(){});
        },{
          // "token":'eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJzZWNhciIsImFwcGtleSI6IjE3NjgyMzA5MDY2Iiwic2VjcmV0IjoiNjJmM2Y4N2U2M2E4ODc0ZjgxN2Q0YzU0OGQ1ZDBlMWMifQ.qbSlKD9jr1Jo0rdpeL_x4Ne3oA7x1xCQSqPpuW45zik'
          "token":_this.token
        })
      },
      formatDate(now) {
        var d=new Date(now);
        var year=d.getFullYear();
        var month=d.getMonth()+1;
        var date=d.getDate();
        if(month<10){month='0'+month}
        if(date<10){date='0'+date}
        return year+"-"+month+"-"+date;
      },
      activate (){
        if(!this.ban){
          var _this = this;
          var inputTxt= /^[a-zA-Z0-9]{10}$/
          if (this.ticketCode == ''){
            this.hint = '请输入激活密钥'
            return false;
          };
          if(!inputTxt.test(this.ticketCode)){
            this.hint = '您输入的密钥有误，请确认后重新输入'
            return false;
          }
          // 激活卡券
          this.$api.post('/ticket/v1/authApi/active?ticketCode='+this.ticketCode, {}, s => {
            _this.productId = s.module;
            _this.buySuite(_this.productId)
          },f=>{
            _this.hint = f.errorMessage;
          },{
              // "token":'eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJzZWNhciIsImFwcGtleSI6IjE3NjgyMzA5MDY2Iiwic2VjcmV0IjoiNjJmM2Y4N2U2M2E4ODc0ZjgxN2Q0YzU0OGQ1ZDBlMWMifQ.qbSlKD9jr1Jo0rdpeL_x4Ne3oA7x1xCQSqPpuW45zik'
              "token":_this.token
          })
        }
      },
      // 到期时间
      expireTime (){
        var ms = this.useExpireTime - new Date().getTime();//时间差
        if(ms<=0){
          clearInterval(this.Method);
          this.type = 0;
          this.hint = '该密钥24小时内未支付已失效，换个试试吧'
          return false;
        }
        var oSec = parseInt(ms/1000);//毫秒转换成秒
        var oDay = parseInt(oSec/86400); //秒转换成天
        oSec%=86400;//不到一天剩下的秒数;
        var oHour = parseInt(oSec/3600);//转换成小时
        if(oHour < 10){oHour = '0'+oHour;}
        oSec%=3600;//不到一小时剩下的秒数;
        var oMin = parseInt(oSec/60);//转换成分钟
        if(oMin < 10){oMin = '0'+oMin;}
        oSec%=60;//不到一分钟剩下的秒数;
        if(oSec < 10){ oSec = '0'+oSec;}
        if(oDay==0){
          this.oDay = 0;
          this.oHour = oHour;
          this.oMin = oMin;
          this.oSec = oSec;
        }else{
          this.oDay = oDay;
          this.oHour = oHour;
          this.oMin = oMin;
          this.oSec = oSec;
        }
      },
      getSuiteId(){
        let _this = this;
        _this.$api.post('/activity/v1/authApi/getIdsByActivity?id=' + this.id,{},s=>{
          s.module.forEach(function(e){

          })
        },f=>{
          _this.open('套餐信息获取失败',false,false,'','','fade_alert',function(){

          });
        },{
          "token": _this.token
        })
      },
      downloadApp(){
        let userAgentObj = navigator.userAgent;
        if(userAgentObj.match(/MicroMessenger/i))
        {
          if(userAgentObj.match(/Android/i)){
            window.location.href = 'http://app.qq.com/#id=detail&appid=1106220919'
          }else if(userAgentObj.match(/iPhone/i)) {
            window.setTimeout(function(){
              window.location.href = "https://itunes.apple.com/cn/app/%E7%94%B5%E6%96%91%E9%A9%AC-%E8%AE%A9%E5%87%BA%E8%A1%8C%E6%9B%B4%E5%AE%89%E5%85%A8/id1252928655?mt=8";
            },200)
          }else{
            window.location.href="http://download.xingjiakeji.com/";
          }
          return;
        }else{
          if(!this.token || this.token == undefined || this.token == ""){
            window.setTimeout(function(){
              if(userAgentObj.match(/Android/i)){
                window.location.href = 'http://app.qq.com/#id=detail&appid=1106220919';
              }else if(userAgentObj.match(/iPhone/i)) {
                window.location.href = "https://itunes.apple.com/cn/app/%E7%94%B5%E6%96%91%E9%A9%AC-%E8%AE%A9%E5%87%BA%E8%A1%8C%E6%9B%B4%E5%AE%89%E5%85%A8/id1252928655?mt=8";
              }
            },200);
            return;
          }
        }
      },
      buySuite(pid){
        let userAgentObj = navigator.userAgent;
        if(userAgentObj.match(/MicroMessenger/i))
        {
          if(userAgentObj.match(/Android/i)){
            window.location.href = 'http://app.qq.com/#id=detail&appid=1106220919'
          }else if(userAgentObj.match(/iPhone/i)) {
            window.setTimeout(function(){
              window.location.href = "https://itunes.apple.com/cn/app/%E7%94%B5%E6%96%91%E9%A9%AC-%E8%AE%A9%E5%87%BA%E8%A1%8C%E6%9B%B4%E5%AE%89%E5%85%A8/id1252928655?mt=8";
            },200)
          }else{
            window.location.href="http://download.xingjiakeji.com/";
          }
          return;
        }else{
          if(!this.token || this.token == undefined || this.token == ""){
            window.setTimeout(function(){
              if(userAgentObj.match(/Android/i)){
                window.location.href = 'http://app.qq.com/#id=detail&appid=1106220919';
              }else if(userAgentObj.match(/iPhone/i)) {
                window.location.href = "https://itunes.apple.com/cn/app/%E7%94%B5%E6%96%91%E9%A9%AC-%E8%AE%A9%E5%87%BA%E8%A1%8C%E6%9B%B4%E5%AE%89%E5%85%A8/id1252928655?mt=8";
              }
            },200);
            return;
          }
        }

        if(this.postState){
          return
        }else{
          this.postState = true;
        }
        const _this = this;
        this.open('恭喜！骑行卡激活成功！<br/>骑30天仅需 9.8元',false,true,'立即购买',function(){
          _this.$api.post('/product/v1/authApi/buy?productId=' + pid,{},s=>{
            _this.postState = false;
            let userAgentObj = navigator.userAgent;
            _this.open('购买成功',false,false,'','','fade_success',function(){
              if(userAgentObj.match(/Android/i)){
                window.control.refreshWallet();
              }else if(userAgentObj.match(/iPhone/i))
              {
                refreshWallet();
              }
              // _this.$router.go(-1)
              _this.info();
              clearInterval(_this.Method);
            });
          },f=>{
            _this.postState = false;
            if(f.resultCode == '30006')
            {
              _this.open('余额不足请先充值！',true,true,'充值',function(){
                let userAgentObj = navigator.userAgent;
                if(userAgentObj.match(/Android/i)){
                  window.control.recharge();
                }else if(userAgentObj.match(/iPhone/i))
                {
                  recharge();
                }
              })
            }else if(f.errorMessage){
              _this.open(f.errorMessage,false,false,'','','fade_alert',function(){

              });
            }else{
              _this.open('购买失败',false,false,'','','fade_alert',function(){

              });
            }
          },{
            "token": _this.token
          })
        },'',function(){
          _this.info();
          _this.postState = false;
        },"")
      },
    },
  }
</script>

<style scoped >
  @import "../styles/styles.css";
  .thumbImg>img{ width: 100%;margin-bottom: -0.03rem;}
  .key span.status1{
    background: #28d078;
  }
  .key span.status2{
    background: #9d9d9d;
  }
  .content{
    width: 100%;
    background: #ff2c2c;
    overflow: hidden;
  }
  .activity-details{
    overflow: hidden;
    width: 100%;
    min-height:4rem;
    }
  .banner{
    position: relative;
    width: 100%;
    height:3.82rem;
    background: url('../styles/asset/tripCard/banners.png') no-repeat;
    background-size: 100% 100%;
  }
  .red-card{
    position: absolute;
    bottom:-2.2rem;
    width: 7.50rem;
    height:5.09rem;
    background: url('../styles/asset/tripCard/red-card.png') no-repeat;
    background-size: 100% 100%;
  }
  .main{
    overflow: hidden;
    width: 7.10rem;
    min-height:3rem;
    padding-top:2.44rem;
    margin:0 auto 0.2rem;
    border-radius: 0 0 0.12rem 0.12rem;
    background: #fff;
  }
  .activate,.payment,.finish{
    overflow: hidden;
    padding-bottom:0.58rem;
  }
  .input-box{
    overflow: hidden;
  }
  .activate input{
    display: block;
    width: 6.4rem;
    height:0.98rem;
    padding:0 0.3rem;
    margin:0 auto 0.2rem;
    font:0.30rem/0.98rem "Microsotf YaHei";
    border:0.01rem solid #d2d2d2;
    border-radius: 0.5rem;
    background: #f5f5f5;
    color:#666;
  }
  .activate .hint{
    width: 6.4rem;
    height:0.36rem;
    margin:0 auto;
    padding-left:0.4rem;
    font:0.24rem/0.36rem "Microsotf YaHei";
    color:#ff2038;
  }
  .activate .activate-btn,.payment .purchase-btn,.finish .purchase-btn{
    width: 6.4rem;
    height:1rem;
    padding:0 0.3rem;
    margin:0.2rem auto 0;
    border-radius: 0.5rem;
    text-align: center;
    font:0.32rem/1rem "Microsotf YaHei";
    box-shadow: 1px 10px 15px #ffdbd1;
    background: #ff4d2d;
    color:#fff;
  }
  .activate .activate-btn.disable{
    background: #d2d2d2;
    box-shadow: 1px 10px 15px #f8f8f8;
  }
  .key{
    margin-top:0.05rem;
    font:0.36rem/0.36rem "Microsotf YaHei";
    font-weight: 600;
    text-align: center;
  }
  .key span{
    position: relative;
    top:-0.04rem;
    vertical-align: middle;
    padding:0.06rem 0.13rem;
    font:0.26rem/0.36rem "Microsotf YaHei";
    font-weight: 500;
    border-radius: 0.1rem;
    background:#3e94ff;
    color:#fff;
  }
  .activation-hint{
    text-align: center;
    font:0.26rem/1rem "Microsotf YaHei";
    color:#999;
  }
  .activation-hint span{
    display: inline-block;
    padding:0.05rem 0.05rem;
    margin:0 0.05rem;
    font:0.26rem/0.26rem "Microsotf YaHei";
    border-radius: 0.04rem;
    background: #ff5d2e;
    color:#fff;
  }
  .activity-rules{
    overflow: hidden;
    position: relative;
    width: 95%;
    min-height:6rem;
    margin:0 auto 0.2rem;
    border-radius:0.12rem;
    background: #fff;
  }
  .rules-title{
    position: absolute;
    top:-0.191rem;
    left:50%;
    margin-left:-1.51rem;
    width: 3.02rem;
    height:1.10rem;
    background:url('../styles/asset/tripCard/titBg.png') no-repeat;
    background-size: 100% 100%;
  }
  .rules-title p{
    margin-top:0.19rem;
    line-height: 0.5rem;
    text-align: center;
    color:#fff;
    font-weight: 600;
  }
  .rules-text{
    padding: 0.95rem 0.35rem 0.75rem;
  }
  .rules-text p{
    margin-bottom:0.05rem;
    font:0.22rem/0.44rem "Microsotf YaHei";
  }
  .rules-text span{
    padding:0.02rem 0.2rem;
    margin-right:0.05rem;
    border-radius:0.3rem;
    background: #ff5d2e;
    color:#fff;
  }
</style>
